package com.atao.order.service.impl;

import com.atao.order.Order;
import com.atao.order.feign.ProductFeignClient;
import com.atao.order.service.OrderService;
import com.atao.product.Product;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.List;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    private DiscoveryClient discoveryClient;

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private LoadBalancerClient loadBalancerClient;

    @Resource
    private ProductFeignClient productFeignClient;

    @Override
    public Order create(Long userId, Long productId) {
        // Product product = getProductRemoteWithLoadBalanced(productId);

        Product product = productFeignClient.getProduct(productId);

        Order order = new Order();
        order.setId(1L);
        order.setUserId(userId);
        order.setNickName("张三");
        order.setAddress("北京");

        order.setTotalPrice(product.getPrice().multiply(new BigDecimal(product.getNum())));

        order.setProductList(List.of(product));
        return order;
    }

    // 第一版：只请求一个商品服务
    private Product getProductRemote(Long productId) {
        // 1、获取到商品服务所在的所有机器ip+port
        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");

        ServiceInstance instance = instances.get(0);
        // 远程url
        String url = "http://" + instance.getHost() + ":" + instance.getPort() + "/product/" + productId;

        log.info("远程请求:{}", url);
        // 2、给远程发送请求
        return restTemplate.getForObject(url, Product.class);
    }

    // 第二版：使用loadBalancerClient进行负载均衡
    private Product getProductRemoteWithLoadBalance(Long productId) {
        // 1、获取到商品服务所在的所有机器ip+port
        //List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
        ServiceInstance choose = loadBalancerClient.choose("service-product");

        // 远程url
        String url = "http://" + choose.getHost() + ":" + choose.getPort() + "/product/" + productId;

        log.info("远程请求:{}", url);
        // 2、给远程发送请求
        return restTemplate.getForObject(url, Product.class);
    }

    // 第三版：使用RestTemplate加上@LoadBalanced注解进行负载均衡
    private Product getProductRemoteWithLoadBalanced(Long productId) {

        // 远程url
        String url = "http://service-product/product/"+productId;

        log.info("远程请求:{}", url);
        // 给远程发送请求
        return restTemplate.getForObject(url, Product.class);
    }
}
